package com.wilcom.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wilcom.system.domain.Maintenance;
import com.wilcom.system.domain.Notification;
import com.wilcom.system.mapper.NotificationMapper;
import com.wilcom.system.model.request.notification.CreateNotification;
import com.wilcom.system.model.request.notification.GetUserNotificationsRequest;
import com.wilcom.system.model.request.notification.IsUnreadMessages;
import com.wilcom.system.service.NotificationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
   
import java.util.Date;

/**
* @author lishi
* @description 针对表【notification】的数据库操作Service实现
* @createDate 2024-06-22 02:34:05
*/
@Service
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification>
    implements NotificationService{

    @Override
    public QueryWrapper<Notification> getQueryWrapper(GetUserNotificationsRequest request) {
        QueryWrapper<Notification> queryWrapper = new QueryWrapper<>();
        Integer userId = request.getUserId();
        queryWrapper.eq("user_id", userId);
//        未读优先 时间越大越靠前
        queryWrapper.orderByDesc( "created_at");
//        is_read = 0 放在前面
        queryWrapper.orderByAsc( "is_read");

        return queryWrapper;
    }

    @Override
    @Transactional
    public Boolean createNotification(CreateNotification createNotification) {
        if (createNotification == null || createNotification.getUserId() == null || createNotification.getMessage() == null){
            return false;
        }
        Notification notification = new Notification();
        notification.setUserId(createNotification.getUserId());
        notification.setMessage(createNotification.getMessage());
        notification.setIsRead(0);
        notification.setCreatedAt(new Date());
        try {
            boolean  res = this.save(notification);
            return res;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Boolean isUnreadMessages(IsUnreadMessages isUnreadMessages) { 
        QueryWrapper<Notification> queryWrapper = new QueryWrapper<>(); 
        queryWrapper.eq("user_id", isUnreadMessages.getUserId());  
        queryWrapper.eq("is_read", 0); 
        return this.count(queryWrapper) > 0; 
    }
}




